package com.chainwintel.prjmgmt.service;

import java.util.List;
import java.util.Set;

import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.chainwintel.prjmgmt.model.MenuItem;
import com.chainwintel.prjmgmt.model.User;
import com.chainwintel.prjmgmt.repository.GenericRepositoryImpl;

@Repository
@Transactional(readOnly = true)
public class UserMgrImpl extends GenericRepositoryImpl<User> implements UserMgr {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4613868961668393591L;

	@Transactional
	public void assignOpers(MenuItem menuItem, User target) throws DataAccessException {
		// TODO Auto-generated method stub
		target = getEntityManager().merge(target);
		menuItem = getEntityManager().merge(menuItem);
		target.getOperations().add(menuItem);
	}

	public User find(long id) throws DataAccessException {
		// TODO Auto-generated method stub
		return this.find(User.class, id);
	}

	public User findByUsernameAndPassword(String username, String password)
			throws DataAccessException {
		// TODO Auto-generated method stub
		return (User) getEntityManager()
		.createQuery(
				"select u from User u where u.username = :uid and u.password = :pwd")
		.setParameter("uid", username).setParameter("pwd", password)
		.getSingleResult();
	}

	@SuppressWarnings("unchecked")
	public List<User> listUsers() throws DataAccessException {
		// TODO Auto-generated method stub
		return getEntityManager().createQuery("select u from User u").getResultList();
	}

	public Set<MenuItem> loadMenu(User user) throws DataAccessException {
		// TODO Auto-generated method stub
		return getEntityManager().merge(user).getOperations();
	}



}
